<template>
	<a-modal
		v-model:open="open"
		title="修改接口"
		@ok="handleOk"
		okText="submit"
		:model="formState"
	>
		<a-form
			ref="formRef"
			:model="formState"
			:label-col="labelCol"
			:wrapper-col="wrapperCol"
		>
			<a-form-item
				label="接口名称"
				name="name"
				:rules="[{ required: true, message: '接口名是必填的哦' }]"
			>
				<a-input v-model:value="formState.name" />
			</a-form-item>
			<a-form-item
				label="接口描述"
				name="description"
				:rules="[{ required: true, message: '接口描述是必填的哦' }]"
			>
				<a-textarea v-model:value="formState.description" />
			</a-form-item>
			<a-form-item
				label="调用地址"
				name="url"
				:rules="[{ required: true }]"
			>
				<a-input v-model:value="formState.url" />
			</a-form-item>
			<a-form-item
				label="请求方法"
				name="method"
				:rules="[{ required: true, message: '请求方法要选一个' }]"
			>
				<a-radio-group v-model:value="formState.method">
					<a-radio value="GET">GET</a-radio>
					<a-radio value="POST">POST</a-radio>
					<a-radio value="DELETE">DELETE</a-radio>
					<a-radio value="OPTIONS">OPTIONS</a-radio>
					<a-radio value="HEAD">HEAD</a-radio>
					<a-radio value="PATCH">PATCH</a-radio>
					<a-radio value="PUT">PUT</a-radio>
					<a-radio value="CONNECT">CONNECT</a-radio>
				</a-radio-group>
			</a-form-item>
			<a-form-item
				label="请求头"
				name="requestHeader"
			>
				<a-textarea v-model:value="formState.requestHeader" />
			</a-form-item>
			<a-form-item
				label="请求参数"
				name="requestParams"
			>
				<a-textarea v-model:value="formState.requestParams" />
			</a-form-item>
			<a-form-item
				label="响应头"
				name="responseHeader"
			>
				<a-textarea v-model:value="formState.responseHeader" />
			</a-form-item>
		</a-form>
	</a-modal>
	<a-table
		:columns="columns"
		:data-source="dataSource"
		:pagination="pagination"
		:loading="loading"
		@change="handleChange"
	>
		<template #headerCell="{ column }">
			<template v-if="column.key === 'name'">
				<span>
					<smile-outlined />
					Name
				</span>
			</template>
		</template>

		<template #bodyCell="{ column, record }">
			<template v-if="column.key === 'name'">
				<a>
					{{ record.name }}
				</a>
			</template>
			<template v-else-if="column.key === 'method'">
				<span>
					<a-tag :color="record.status === 1 ? 'green' : 'red'">
						{{ record.method }}
					</a-tag>
				</span>
			</template>
			<template v-else-if="column.key === 'url'">
				<a
					v-if="record.method === 'GET'"
					:href="record.url"
					target="_blank"
					>{{ record.url }}
				</a>
				<span v-else>{{ record.url }}</span>
			</template>
			<template v-else-if="column.key === 'updateTime'">
				{{ record.updateTime }}
			</template>
			<template v-else-if="column.key === 'createTime'">
				{{ record.createTime }}
			</template>
			<template v-else-if="column.key === 'action'">
				<a-space wrap>
					<a-button
						type="primary"
						@click="showModal(record)"
						>Modify
					</a-button>
					<a-button
						type="primary"
						@click="handleDelete(record.id)"
						danger
						>delete
					</a-button>
					<a-button type="primary">online</a-button>
				</a-space>
			</template>
		</template>
	</a-table>
</template>
<script lang="ts" setup>
import api from '@/api';
import { ExclamationCircleOutlined, SmileOutlined } from '@ant-design/icons-vue';
import { usePagination } from 'vue-request';
import type { FormInstance } from 'ant-design-vue';
import { message, Modal } from 'ant-design-vue';

import { createVNode, onBeforeMount, reactive, ref, type UnwrapRef } from 'vue';
import { ApplicationResponseStatusCodeEnum } from '@/enums/ApplicationResponseStatusCodeEnum';
import PageInterfaceInfo = API.PageInterfaceInfo;
import InterfaceInfo = API.InterfaceInfo;
import InterfaceInfoUpdateRequest = API.InterfaceInfoUpdateRequest;
import InterfaceInfoQueryRequest = API.InterfaceInfoQueryRequest;

const open = ref<boolean>(false);
const labelCol = { style: { width: '150px' } };
const wrapperCol = { span: 14 };
const columns = [
	{
		title: 'id',
		dataIndex: 'id',
		key: 'id',
	},
	{
		title: '接口名称',
		dataIndex: 'name',
		key: 'name',
	},
	{
		title: '接口描述',
		dataIndex: 'description',
		key: 'description',
	},
	{
		title: '请求方式',
		dataIndex: 'method',
		key: 'method',
	},
	{
		title: '接口地址',
		dataIndex: 'url',
		key: 'url',
	},
	{
		title: '请求头',
		dataIndex: 'requestHeader',
		key: 'requestHeader',
		valueType: 'jsonCode',
	},
	{
		title: '请求参数',
		dataIndex: 'requestParams',
		key: 'requestParams',
		valueType: 'jsonCode',
	},
	{
		title: '创建时间',
		dataIndex: 'createTime',
		key: 'createTime',
	},
	{
		title: '更新时间',
		dataIndex: 'updateTime',
		key: 'updateTime',
	},
	{
		title: '操作',
		key: 'action',
	},
];
const dataRaw = ref<PageInterfaceInfo>({
	records: [],
	total: 0,
	size: 10,
	current: 1,
});

const formRef = ref<FormInstance>();
const showModal = (record: InterfaceInfo) => {
	formState.name = record.name;
	formState.description = record.description;
	formState.url = record.url;
	formState.method = record.method;
	formState.requestHeader = record.requestHeader;
	formState.responseHeader = record.responseHeader;
	formState.requestParams = record.requestParams;
	formState.status = record.status;
	formState.id = record.id;
	open.value = true;
};

const formState: UnwrapRef<InterfaceInfoUpdateRequest> = reactive({
	name: '',
	description: '',
	url: '',
	method: '',
	requestHeader: '',
	responseHeader: '',
	requestParams: '',
	status: 1,
});
const {
	data: dataSource,
	run,
	loading,
	current,
	pageSize,
} = usePagination(
	(params: InterfaceInfoQueryRequest) =>
		api.interfaceInfoController.listInterfaceInfoByPage(params).then(res => {
			pagination.value.total = Number.parseInt(res.data.data.total);
			return res.data.data.records;
		}),
	{
		pagination: {
			currentKey: 'current',
			pageSizeKey: 'pageSize',
		},
		onSuccess: (data, params) => {
			console.log('data', data);
			console.log('params', params);
		},
		onError: (error, params) => {
			console.log('error', error);
			console.log('params', params);
		},
	},
);

const pagination = ref({
	total: 0,
	current: current.value,
	pageSize: pageSize.value,
});
const handleChange = (pag: { pageSize: number; current: number }) => {
	pagination.value.current = pag.current;
	run({ ...pag });
};
const handleOk = async () => {
	try {
		await formRef.value.validate();
		api.interfaceInfoController
			.updateInterfaceInfo(formState)
			.then(() => {
				message.success('更新成功', 2);
				open.value = false;
			})
			.catch(errorInfo => {
				message.error(`操作失败:${errorInfo}`, 2);
			});
		open.value = false;
	} catch (errorInfo) {
		message.error('好像还有东西没填', 2);
		console.log('Failed:', errorInfo);
	}
};
const handleDelete = async (id: number) => {
	Modal.confirm({
		cancelText: '取消',
		okText: '确定',
		title: '确定要删除吗？',
		icon: createVNode(ExclamationCircleOutlined),
		onOk: async () => {
			message.loading('正在删除');
			open.value = false;
			api.interfaceInfoController
				.deleteInterfaceInfo({ id })
				.then(() => {
					message.destroy();
					message.success('删除成功', 2);
				})
				.catch(errorInfo => {
					message.destroy();
					message.error(`操作失败:${errorInfo}`, 2);
				});
		},
	});
};

onBeforeMount(() => {
	message.loading('正在加载数据', 0);
	api.interfaceInfoController
		.listInterfaceInfoByPage({
			current: 1,
			pageSize: 10,
		})
		.then(res => {
			message.destroy();
			const applicationResponse = res.data;
			if (applicationResponse.code === ApplicationResponseStatusCodeEnum.SUCCESS.valueOf()) {
				dataRaw.value = applicationResponse.data;
				pagination.value.total = Number.parseInt(applicationResponse.data.total);
				message.success('数据获取成功', 3);
			} else {
				message.error(`数据获取失败: ${applicationResponse.message || '未知错误'}`, 3);
			}
		})
		.catch(err => {
			message.destroy();
			message.error(`数据获取失败: ${err.message}`, 3);
		});
});
</script>
